/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package staplers;

import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.NamingContainer;
import javax.faces.context.FacesContext;

/**
 *
 * @author robert
 */
@ManagedBean
@SessionScoped
public class CartCTRL {
    DBHelper helper;
    Order order;
    int newItemQuantity = 1;
    private Order orderReceipt;

    /** Creates a new instance of CartCTRL */
    public CartCTRL() {
        helper = ((UserCTRL)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("userCTRL")).getHelper();
        this.createOrder(((UserCTRL)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("userCTRL")).getUser());
    }

    public int getNewItemQuantity() {
        return newItemQuantity;
    }

    public void setNewItemQuantity(int newItemQuantity) {
        this.newItemQuantity = newItemQuantity;
    }    

    public Order getOrder() {
        return order;
    }
    
    public Order getReceipt()
    {
        return this.orderReceipt;
    }
    
    public void createOrder(User user)
    {
        order = new Order(user);
        order.setOrderLinks(new HashSet<OrderLink>(0));
    }
    
    public void destroyOrder()
    {
        order = null;
    }
    
    public String addToCart()
    {
        Item item = ((ItemCTRL)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("itemCTRL")).getItem();
        if (item.getStock() ==0 )
        {
            ((UserCTRL)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("userCTRL")).setErrMsg("Out of stock");
            return "ItemPage";
        }
        
        if (item.getStock() < newItemQuantity)
        {
            ((UserCTRL)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("userCTRL")).setErrMsg("Insufficient stock");
            return "ItemPage";
        }
        
        Iterator<OrderLink> iter = order.getOrderLinks().iterator();
        boolean alreadyInCart = false;
        while (iter.hasNext())
        {
            OrderLink ol = iter.next();
            if (ol.getItem().getId() == item.getId())
            {
                alreadyInCart = true;
                ol.setQ(ol.getQuantity()+newItemQuantity);
                break;
            }
        }
        if (!alreadyInCart)
        {
            OrderLink ol = new OrderLink(order,item,newItemQuantity, true);
            order.getOrderLinks().add(ol);
        }        
        //order.setAmount(order.getAmount().add(item.getPrice().multiply(BigDecimal.valueOf((double)newItemQuantity))));
        
        ((UserCTRL)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("userCTRL")).setErrMsg("Item added to cart");
             
                
        newItemQuantity = 1;
                
        return "ItemPage";
    }
    
    public String submitPayment()
    {
        if (!order.getIsEmpty()) 
        {
            boolean errors = false;
            for (OrderLink ol : order.getOrderLinks())
            {
                Item item = helper.getStockById(ol.getItem().getId());
                if (item.getStock()-ol.getQuantity() < 0 )
                {
                    ol.setQ(item.getStock());
                    ol.setItem(item);
                    errors = true;
                }
            }
            if (errors)
            {
              ((UserCTRL)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("userCTRL")).setErrMsg("Someone bought something before you had a chance! Please review your cart.");  
              return "CheckOut";
            }
            order.setDate(new Date());
            helper.finalizeOrder(order);
            helper.finalizeOrderLinks(order.getOrderLinks());
            helper.deductStockAfterOrder(order.getOrderLinks());
            orderReceipt = order;
            this.createOrder(((UserCTRL)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("userCTRL")).getUser());
        }
        
        //TODO: This should generate a receipt
        return "Receipt";
    }
    
    public String updateCart()
    {       
        
        Iterator<OrderLink> iter = order.getOrderLinks().iterator();
        
        while (iter.hasNext())
        {
            OrderLink ol = iter.next();
            if (ol.isSelected())
            {
                ol.setQ(0);
                iter.remove();
            }
        }
        ((UserCTRL)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("userCTRL")).setErrMsg("Cart updated");
        return "ManageCart";
    }

}
